import axios from "axios"
import Qs from 'qs'
import {
  Toast
} from "vant"

import log from './log.js';
import store from './store.js';

axios.defaults.baseURL = "/api"
axios.defaults.timeout = 5000





// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  })

function post(url, data, opt={}) {

  return new Promise((resp, rej) => {
      let loadBox
      if( !opt.noToast ){
        loadBox=Toast.loading({
          message:  opt.msg ||  '加载中...',
          forbidClick: true,
          loadingType : 'spinner',
        })
      }
      // 
      let userinfo = store('userinfo')
      if(  userinfo ) {
        data.__token__ = userinfo.token || '__token__'
        data.__ssid__ = userinfo.ssid || '__ssid__'
      }
      axios.post(url, Qs.stringify(data))
        .then(res => {
          if(!opt.noToast) loadBox.clear()
          resp(res.data)
        })
        .catch(err => {
          log({
            type : 'error',
            msg : 'post err : ' + err
          })
          if(!opt.noToast) loadBox.clear()
          rej(err)
        })
      
    })
    
}

export default post
